//import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
//import 'package:amap_location_flutter_plugin/amap_location_option.dart';
import '../../app_files.dart';
import 'package:flutter_location/flutter_location.dart';
import 'dart:io' show Platform;

class LocationManager {
  static LocationManager _globalLocationManager;

  static LocationManager get locationManager =>
      _globalLocationManager ??= LocationManager();

  LocationData _lastLocation;

  LocationManager() {
    _init();
  }

  _init() async {
//    _locationFlutterPlugin.requestLocationPermission();
  }

  setLocationInfo(LocationData _info) {}

  getLocation({bool needAddress = false}) async {
    if (Platform.isIOS) {
      if (_lastLocation != null) {
        DateTime now = DateTime.now();
        DateTime time = DateTime.tryParse(_lastLocation.time);
        var diff = time.difference(now);
        if (diff.inSeconds < 10) return _lastLocation;
      }
      LocationResult result = await FlutterLocation.getLocation();
      if (result.res == 0) {
        _lastLocation = result.locationData;
        return result.locationData;
      } else {
        return null;
      }
    } else {
      if (_lastLocation != null) {
        DateTime now = DateTime.now();
        DateTime time = DateTime.tryParse(_lastLocation.time);
        var diff = time.difference(now);
        if (diff.inMinutes < 10) {
          if (!needAddress)
            return _lastLocation;
          else {
            if (_lastLocation.city.length != 0) return _lastLocation;
          }
        }
      }
      LocationResult result = await FlutterLocation.getLocation();
      _lastLocation = result.locationData;
      if (needAddress) {
        _lastLocation = await addressGeocode(_lastLocation);
      }
//            _lastLocation = LocationData(
//        latitude: 37.785834,
//        longitude: -122.406417,
//        time: DateTime.now().toString(),
//      );
      return _lastLocation;
    }
  }

  static addressGeocode(LocationData data) async {
    return data;
    // ResultData res =
    //     await CommonNetWork.baiduGecodingApi(data.latitude, data.longitude);
    // if (res.success) {
    //   Map geoInfo = res.data['data']['addressComponent'];
    //   String district = CommonUtils.checkNullToString(geoInfo['district']);
    //   String country = CommonUtils.checkNullToString(geoInfo['country']);
    //   String city = CommonUtils.checkNullToString(geoInfo['city'])
    //       .replaceAll(RegExp('市'), '');
    //   LocationData loc = LocationData(
    //     time: CommonUtils.checkNullToString(data.time),
    //     latitude: data.latitude,
    //     longitude: data.longitude,
    //     city: city,
    //     country: country,
    //     district: district,
    //     address: CommonUtils.checkNullToString(
    //         res.data['data']['formatted_address']),
    //   );
    //   return loc;
    // }
    // return data;
  }
}
